<!DOCTYPE html>
<head>
    <title>socketio 通讯</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="//cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>

<style>
    .group_name {margin: 0 auto; font-size: 40px; color: #000000; text-align: center; }
    input {display: block; width: 90%; height: 100px; line-height: 100px; font-size: 40px; color: #000; background-color: aqua; margin: 20px auto;}
    input::placeholder {font-size: 24px; color: #000; }
    button {display: block; width: 50%; height: 80px; font-size: 40px; color: #fff; background-color: #ec9d9d; margin: 20px auto;}
    .list {margin: 0 auto; width: 90%; font-size: 40px;}
</style>

<div class="group_name">{$group_name}</div>

<input type="text" name="username" id="username" placeholder="输入用户名"/>
<input type="text" name="message" id="message" placeholder="输入信息"/>

<button onclick="addUsername()">进入聊天室</button>
<button onclick="sendMsg()">发送消息</button>

<div class="list" id="list">
    <ul>
        <li>我是聊天内容</li>
    </ul>
</div>

<script type="text/javascript" src="//cdn.bootcss.com/socket.io/2.0.3/socket.io.js"></script>
<script>
    var socket = io("http://127.0.0.3:8888");  // ip

    // 连接成功
    socket.on('connect', function () {
        console.log('------连接成功--后台默认发送消息----->');
    });

    // 监听success
    socket.on('success', function (data) {
        console.log('success')
        data  = JSON.parse(data);
        console.log(data)
        console.log('-----success------->' + data);
    });

    // 监听chat message
    socket.on('group message', function (data) {
        data  = JSON.parse(data);
        let html = "<li>" + data.message + "</li>"
        $("#list ul").append(html);
    });

    // 进入聊天室
    function addUsername(){
        let username = $("#username").val();
        if(username == ''){
            console.log('请输入用户名');
            return false;
        }
        socket.emit("login", {'username' : username, 'group_id' : "ground_{$group_id}"});
    }

    function sendMsg(){
        let message = $("#message").val();
        if(message == ''){
            console.log('请输入发送信息');
            return false;
        }
        socket.emit("group", {'message' : message, 'group_id' : "ground_{$group_id}"});
    }
</script>

</body>
</html>